﻿using eDoc.DAL;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using eDocWS.Objects;

namespace eDocWS.Common
{
    public class PrivateFuncs
    {        
        private readonly string AuthenUrl = ConfigurationManager.AppSettings["AuthenUrl"];
        public PrivateFuncs()
        {

        }
        public Message InsertDevice(MainDB db, string Uuid, string Email, string Password, string AppID, string Push_ID, string iPadName)
        {
            Message message = new Message();

            DataTable dtInsert = db.StoredProcedures.VNA_Insert_Devices(Uuid, Email.ToLower(), Password, true, AppID, Push_ID, iPadName);
            
            if (dtInsert.Rows[0][0].ToString() == "1")
            {
                message.Title = "Active success";
                message.Content = "Active: " + Uuid + " with email: " + Email + " success!";
                message.Result = true;
            }
            else
            {

                message.Title = "This device is already activated";
                message.Content = "This device is already activated: " + Uuid + " with email : " +
                                  Email +
                                  " success!";
                message.Result = true;
            }


            return message;
        }

        /// <summary>
        /// So sanh version : flag = 0 : cung version; flag = 1: la version moi; flag = -1 : version hien tai; flag=-2: loi
        /// </summary>
        /// <param name="oldVersion"></param>
        /// <param name="newVersion"></param>
        /// <returns></returns>
        public int CompareVersion(string oldVersion, string newVersion)
        {
            int flag = 0;
            try
            {
                var versionOld = new Version(oldVersion);
                var versionNew = new Version(newVersion);
                flag = versionNew.CompareTo(versionOld);
            }
            catch(Exception ex)
            {
                flag = -2;
            }
            return flag;
        }

        /// <summary>
        /// Neu co trong blacklist thi tra ve false, neu khong co tra ve true
        /// </summary>
        /// <param name="uuid"></param>
        /// <returns></returns>
        public bool CheckBlacklist(string uuid)
        {
            bool flag = false;
            DataTable dtBlacklist = new DataTable();
            using (MainDB db = new MainDB())
            {
                dtBlacklist = db.StoredProcedures.VNA_Select_Blacklist_by_Uuid(uuid);
                db.Close();
                db.Dispose();
            }

            if (dtBlacklist == null || dtBlacklist.Rows.Count == 0)
            {
                flag = true;
            }

            return flag;
        }

        /// <summary>
        /// Kiem tra xem email co phai la email supper hay khong (dc active nhieu device)
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool CheckEmailSupper(string email)
        {
            DataTable dtEmailSupper = new DataTable();
            using (MainDB db = new MainDB())
            {
                dtEmailSupper = db.StoredProcedures.VNA_Select_Emails();
                db.Close();
                db.Dispose();
            }
            if (dtEmailSupper == null || dtEmailSupper.Rows.Count == 0)
            {
                return false;
            }
            else
            {
                for (int i = 0; i < dtEmailSupper.Rows.Count; i++)
                {
                    if (email.Trim().ToLower() == dtEmailSupper.Rows[i]["Email"].ToString().Trim().ToLower())
                    {
                        return true;
                    }
                }
                return false;
            }
        }

        public ResponseAuthen GetAuthen(RequestAuthen requestAuthen)
        {
            ResponseAuthen result = new ResponseAuthen();
            try
            {
                var serializer = new JavaScriptSerializer();
                string serializedResult = serializer.Serialize(requestAuthen);
                string data = get_web_content(AuthenUrl + serializedResult);
                if (!string.IsNullOrEmpty(data))
                {
                    result = serializer.Deserialize<ResponseAuthen>(data);
                }
            }
            catch (Exception ex)
            {
                Global.log.Error("Error Authen :" + ex);
                result.MessageError = ex.Message + "::" + ex.StackTrace;  
            }
            return result;
        }



        private string get_web_content(string url)
        {

            Uri uri = new Uri(url);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            request.Method = WebRequestMethods.Http.Get;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader reader = new StreamReader(response.GetResponseStream());

            string output = reader.ReadToEnd();

            response.Close();

            return output;

        }
    }
}